package com.fho4565.commands;

import com.fho4565.core.cdgroup.CommandGroup;
import com.fho4565.core.cdgroup.CommandGroupList;
import com.fho4565.main.Configs;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.mojang.brigadier.CommandDispatcher;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import net.minecraft.commands.CommandSourceStack;
import net.minecraftforge.event.world.WorldEvent;
import org.jetbrains.annotations.NotNull;

import java.util.Objects;

import static com.mojang.brigadier.arguments.StringArgumentType.getString;
import static com.mojang.brigadier.arguments.StringArgumentType.string;
import static net.minecraft.commands.Commands.argument;
import static net.minecraft.commands.Commands.literal;
//TODO 1.3.0完成
public class CommandGroupCommand {
    private static final TypeToken<CommandGroupList> type = new TypeToken<>() {
    };
    private static CommandGroupList commandGroupList;
    private static final Gson gson = new GsonBuilder().create();
    private static void save() {
        Configs.commandGroupList.set(gson.toJson(commandGroupList));
        Configs.commandGroupList.save();
    }
    private static void read() {
        String json = Configs.commandGroupList.get();
        if (json.isEmpty()) {
            commandGroupList = new CommandGroupList();
            return;
        }
        CommandGroupList map = gson.fromJson(json, type.getType());
        commandGroupList = Objects.requireNonNullElseGet(map, CommandGroupList::new);
    }

    public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
        dispatcher.register(
                literal("cdgroup")
                        .then(add())
                        .then(remove())
                        .then(modify())
                        .then(list())
        );
    }

    @NotNull
    private static LiteralArgumentBuilder<CommandSourceStack> list() {
        return literal("list");
    }

    @NotNull
    private static LiteralArgumentBuilder<CommandSourceStack> modify() {
        return literal("modify");
    }

    @NotNull
    private static LiteralArgumentBuilder<CommandSourceStack> remove() {
        return literal("remove");
    }

    @NotNull
    private static LiteralArgumentBuilder<CommandSourceStack> add() {
        return literal("add").then(argument("name", string()).executes(context -> {
                    if (commandGroupList.contains(getString(context, "name"))) {
                        return 0;
                    } else {
                        commandGroupList.add(new CommandGroup(getString(context, "name")));
                        save();
                        return 1;
                    }
                })
        );
    }

    //@SubscribeEvent
    public static void onLoad(WorldEvent.Load event) {
        read();
    }
}
